import getUserTempId from "@/utils/userTempId";
import {reqLogin, reqLogOut, reqUserInfo} from "@/api";

const state = {
    userTempId:getUserTempId(),
    token:localStorage.getItem("token") || "",
    userInfo:{
        nickName:""
    }
}
const mutations = {
    SET_TOKEN_STATE(state, payload) {
        state.token = payload.token
    },
    SET_USERINFO_STATE(state,payload){
        state.userInfo = payload.userInfo
    },
    REMOVE_STATE(state) {
        state.token = "";
        state.userInfo = {nickName: ""};
        localStorage.removeItem("token")
    }
}
const actions = {
    async getToken({commit},userInfo){
        try {
            const result =  await reqLogin(userInfo)
            localStorage.setItem("token",result.token)
            commit("SET_TOKEN_STATE",{token:result.token})
        }catch (e){
            return Promise.reject(e)
        }
    },
    async getUserInfo({commit}){
        try {
            const result = await reqUserInfo()
            commit("SET_USERINFO_STATE",{userInfo:result})
        }catch (e){
            return Promise.reject(e)
        }
    },
    getRemove({commit}){
        commit("REMOVE_STATE")
    },
    async getLogOut({commit}){
        try{
            await reqLogOut()
            commit("REMOVE_STATE")
        }catch (e){
            return Promise.reject(e)
        }
    }
}
export default {
    namespaced:true,
    state,
    actions,
    mutations
}